<?php

/**
 * 在微信公众平台配置此接口
 * 如：http://admin.demo.com/index.php?m=admin&c=Interface&a=response
 */
namespace Admin\Controller;

use Common\Controller\ControllerBaseWeixin as BaseWeixin;
use Common\Model\UserModel as User;
use Common\Model\ConfigModel as Config;
use Common\Model\WxBasicReplyModel as WxBasicReply;

class InterfaceController extends BaseWeixin
{

    /**
     * [subscribe 订阅]
     *
     * @return [type] [description]
     */
    public function subscribe($obj)
    {
        parent::subscribe($obj);
        $this->default_answer($obj, 'subscribe');
    }

    /**
     * [answer 普通文本事件]
     *
     * @return [type] [description]
     */
    public function answer($obj)
    {
        $keyword = $this->keyword;
        $this->default_answer($obj , $keyword);
    }

    /**
     * [clickEvent 自定义菜单点击事件]
     *
     * @param [type] $obj
     *            [description]
     * @return [type] [description]
     */
    public function clickEvent($obj)
    {
        $key = $obj->EventKey;
        $this->default_answer($obj, $key);

//         switch ($key) {
//             case "ccc":
//                 //do something;
//                 break;
//             default:
//                 break;
//         }
    }

    /**
     * 扫描事件
     * @param unknown $obj            
     */
    public function ScanEvent($obj)
    {
        
        $code = (string)$obj->EventKey;
        
        if( $this->userInfo && $this->userInfo['flag']==0 ){
            $u = new User();
            $u->addFans($code, $this->uid , 4 );
        }
        
        $this->default_answer($obj, 'scan');
    }

    /**
     * [viewEvent 自定义菜单URL事件]
     *
     * @param [type] $obj
     *            [description]
     * @return [type] [description]
     */
    public function viewEvent($obj)
    {
        $key = $obj->EventKey;
        echo "";
        die();
    }


    /**
     * 默认回复
     */
    private function default_answer($obj, $keyword="")
    {
        $WxBasicReply = new WxBasicReply();
        $keyword = $keyword ? $keyword : $this->keyword;
        $WxBasicReplyAnswer = $WxBasicReply->answer( $keyword );
        if($WxBasicReplyAnswer){
            $welcome = $WxBasicReplyAnswer;
        }else{
            $config = new Config();
            $welcome = $config->getConfig("DEFAULT_REPLY_TXT");
        }

        if ($welcome)
        {
            
            $order = array(
                "\r\n",
                " ",
                "\n",
                "\r",
                "\t"
            );
            $welcome_tmp = str_replace($order, '', $welcome);
            $data = json_decode($welcome_tmp, true);
        }
    
        if (is_array($data))
        {
            $this->sendPicMsg($data);
        } else if ($welcome)
        {
            $welcome = htmlspecialchars_decode($welcome, ENT_QUOTES);
            $this->sendTextMsg($welcome);
        } else
        {
            echo "";
        }
    }
    
    
}